/**
 * UserLoginController.java
 * Version 1.0.0
 * Created on 2018年7月11日
 *
 */
package com.yincheng.oes.sso.controller;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.yincheng.oes.sso.LoginResponse;
import com.yincheng.oes.sso.RegisterResponse;
import com.yincheng.oes.sso.entity.User;
import com.yincheng.oes.sso.service.AuthService;
import com.yincheng.oes.sso.service.UserService;
import com.yincheng.oes.sso.util.SmsUtil;

/**
 * @author yangsy
 * @version 1.0.0
 * @since
 * 创建时间：2018年7月11日
 * 功能描述：用户登录相关控制层
 * 邮箱地址：446948434@qq.com
 */
@Controller
@RequestMapping("")
public class UserLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    static final String failure = "FAIL";
    static final String success = "OK";

    /**
     * 用户登录
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) {
        String userAccount = request.getParameter("userAccount");
        String psd = request.getParameter("psd");
        if (userAccount == null || userAccount == "") {
            model.addAttribute("msg", "账号为空");
            return "login";
        }
        User user = userService.getUserByUserAccount(userAccount);
        if (user == null) {
            model.addAttribute("msg", "该账号不存在");
            return "login";
        }
        if (!user.getPassword().equals(psd)) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
        // String sessionId = request.getSession().getId();
        request.getSession().setAttribute("userName", user.getUserName());
        request.getSession().setAttribute("userId", user.getUserId());
        request.getSession().setAttribute("userAccount", user.getUserAccount());
        model.addAttribute("user", user);
        model.addAttribute("menu", authService.getMenuAuthList(user.getUserId()));

        // user.setSessionId(sessionId);
        // userService.saveUserSessionId(account);

        return "default";

    }

    /**
     * 校验登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkLogin.json", method = RequestMethod.POST)
    @ResponseBody
    public LoginResponse checkLogin(HttpServletRequest request) {
        LoginResponse response = new LoginResponse();
        String userAccount = request.getParameter("userAccount");
        String psd = request.getParameter("psd");
        if (userAccount == null || userAccount == "") {
            response.setCode(failure);
            response.setMessage("账号为空");
            return response;
        }
        User user = userService.getUserByUserAccount(userAccount);
        if (user == null) {
            response.setCode(failure);
            response.setMessage("该账号不存在");
            return response;
        }
        if (!user.getPassword().equals(psd)) {
            response.setCode(failure);
            response.setMessage("密码错误");
            return response;
        }
        response.setCode(success);
        response.setMessage("");
        return response;
    }

    /**
     * 跳转至登录页面
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 获取校验码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getCode.json", method = RequestMethod.GET)
    @ResponseBody
    public SendSmsResponse getCode(HttpServletRequest request) {
        String telePhone = request.getParameter("telePhone");
        String type = request.getParameter("type");
        String code = getSix();
        request.getSession().setAttribute(telePhone, code);
        try {
            SendSmsResponse smsResponse = SmsUtil.sendSms(telePhone, code, type);
            return smsResponse;
        } catch (ClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 注册学生用户
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/register.json", method = RequestMethod.POST)
    @ResponseBody
    public RegisterResponse register(HttpServletRequest request) {
        RegisterResponse response = new RegisterResponse();
        String userName = request.getParameter("userName");
        if (StringUtils.isEmpty(userName)) {
            response.setCode(failure);
            response.setMessage("用户姓名为空");
            return response;
        }
        String userAccount = request.getParameter("userAccount");
        if (StringUtils.isEmpty(userAccount)) {
            response.setCode(failure);
            response.setMessage("用户账号为空");
            return response;
        }
        User user = userService.getUserByUserAccount(userAccount);
        if (user != null) {
            response.setCode(failure);
            response.setMessage("该用户已被注册过");
            return response;
        }
        String psd = request.getParameter("psd");
        if (StringUtils.isEmpty(psd)) {
            response.setCode(failure);
            response.setMessage("密码为空");
            return response;
        }
        String code = request.getParameter("code");
        Object eCode = request.getSession().getAttribute(userAccount);
        if (StringUtils.isEmpty(code)) {
            response.setCode(failure);
            response.setMessage("验证码为空");
            return response;
        }
        if (!code.equals(eCode)) {
            response.setCode(failure);
            response.setMessage("验证码不正确");
            return response;
        }
        user = new User();
        user.setPassword(psd);
        user.setUserAccount(userAccount);
        user.setUserName(userName);
        userService.createStudentUser(user);
        response.setCode(success);
        return response;
    }

    /**
     * 重置用户密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/resetPsd.json", method = RequestMethod.POST)
    @ResponseBody
    public RegisterResponse resetPsd(HttpServletRequest request) {
        RegisterResponse response = new RegisterResponse();
        String userAccount = request.getParameter("userAccount");
        if (StringUtils.isEmpty(userAccount)) {
            response.setCode(failure);
            response.setMessage("用户名为空");
            return response;
        }
        User user = userService.getUserByUserAccount(userAccount);
        if (user == null) {
            response.setCode(failure);
            response.setMessage("该账号尚未注册");
            return response;
        }
        String psd = request.getParameter("psd");
        if (StringUtils.isEmpty(psd)) {
            response.setCode(failure);
            response.setMessage("密码为空");
            return response;
        }
        String code = request.getParameter("code");
        Object eCode = request.getSession().getAttribute(userAccount);
        if (StringUtils.isEmpty(code)) {
            response.setCode(failure);
            response.setMessage("验证码为空");
            return response;
        }
        if (!code.equals(eCode)) {
            response.setCode(failure);
            response.setMessage("验证码不正确");
            return response;
        }
        user.setPassword(psd);
        userService.saveUser(user);
        response.setCode(success);
        return response;
    }

    public static String getSix() {
        Random rad = new Random();

        String result = rad.nextInt(1000000) + "";
        if (result.length() != 6) {
            return getSix();
        }
        return result;
    }

}
